package com.oa.ylms.apps.dao.plan.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.constants.IDEDStates;
import com.oa.ylms.apps.dao.plan.ICheckPlanCategoryDao;
import com.oa.ylms.apps.entity.plan.CheckPlanCategoryValue;

public class CheckPlanCategoryDaoImpl extends HibernateDaoSupport implements ICheckPlanCategoryDao {
	List<CheckPlanCategoryValue> list;
	
	@Override
	public int addCheckPlanCategory(CheckPlanCategoryValue checkPlanCategory)
			throws Exception {
		if(checkPlanCategory != null){
			this.getHibernateTemplate().save(checkPlanCategory);
			return checkPlanCategory.getCategoryId();
		}
		return 0;
	}

	@Override
	public boolean editCheckPlanCategory(
			CheckPlanCategoryValue checkPlanCategory) throws Exception {
		if(checkPlanCategory != null){
			try{
				this.getHibernateTemplate().update(checkPlanCategory);
			}catch(Exception e){
				return false;
			}
			return true;
		}
		return false;
	}

	@Override
	public CheckPlanCategoryValue queryByCategoryId(
			CheckPlanCategoryValue checkPlanCategory) throws Exception {
		if(checkPlanCategory != null){
			return (CheckPlanCategoryValue)this.getHibernateTemplate().get(CheckPlanCategoryValue.class, checkPlanCategory.getCategoryId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CheckPlanCategoryValue> queryCheckPlanCategory(
			final CheckPlanCategoryValue checkPlanCategory) throws Exception {
		String hqlStr = "FROM CheckPlanCategoryValue cpcv WHERE 1=1";
		if(checkPlanCategory.getStates() != null){
			hqlStr += " AND cpcv.states = ?";
		}
		hqlStr += " AND cpcv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if(checkPlanCategory.getStates() != null){
					query.setInteger(++index, checkPlanCategory.getStates());
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}

	public List<CheckPlanCategoryValue> getList() {
		return list;
	}

	public void setList(List<CheckPlanCategoryValue> list) {
		this.list = list;
	}

}
